package com.wzy.oa_sys.service.impl.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.oa_sys.mapper.schedule.BoardroomMapper;
import com.wzy.oa_sys.mapper.schedule.UseBoardroomMapper;
import com.wzy.oa_sys.model.pojo.schedule.OaBoardroom;
import com.wzy.oa_sys.model.pojo.schedule.OaUseBoardroom;
import com.wzy.oa_sys.model.request.schedule.UseBoardroomReq;
import com.wzy.oa_sys.model.response.schedule.UseBoardroomDataResp;
import com.wzy.oa_sys.service.schedule.BoardroomService;
import com.wzy.oa_sys.service.schedule.UseBoardroomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class UseBoardroomServiceImpl extends ServiceImpl<UseBoardroomMapper, OaUseBoardroom> implements UseBoardroomService {
    @Autowired
    private UseBoardroomMapper useBoardroomMapper;

    @Autowired
    private BoardroomMapper boardroomMapper;

    /**
     * 检查会议室在指定时间段是否被占用
     * @return true表示被占用，false表示可用
     */
    public boolean checkBoardroomOccupied(UseBoardroomReq useBoardroomReq) {
        // 参数验证
        if (useBoardroomReq.getStarttime() == null || useBoardroomReq.getDeadline() == null) {
            throw new IllegalArgumentException("时间参数不能为空");
        }

        if (useBoardroomReq.getStarttime().isAfter(useBoardroomReq.getDeadline())) {
            throw new IllegalArgumentException("开始时间不能晚于结束时间");
        }

        // 查询该时间段是否有重叠的预约
        List<OaUseBoardroom> overlappingBookings = useBoardroomMapper.findOverlappingBookings(useBoardroomReq);

        boolean empty = overlappingBookings.isEmpty();
        System.out.println("是否有重叠的预约：" + empty);
        return !empty;
    }

    @Override
    public List<UseBoardroomDataResp> getBoardroomSchedules() {
        List<OaUseBoardroom> oaUseBoardrooms = useBoardroomMapper.selectList(null);
        List<UseBoardroomDataResp> useBoardroomDataResps = new ArrayList<>();
        for (OaUseBoardroom oaUseBoardroom : oaUseBoardrooms) {
            QueryWrapper<OaBoardroom> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("n_boardroom_id", oaUseBoardroom.getNBoardroomId());
            OaBoardroom oaBoardroom = boardroomMapper.selectOne(queryWrapper);
            useBoardroomDataResps.add(UseBoardroomDataResp.builder()
                    .cno(oaBoardroom.getCNo())
                    .starttime(oaUseBoardroom.getDtStartTime())
                    .deadline(oaUseBoardroom.getDtDeadline())
                    .build());
        }
        return useBoardroomDataResps;
    }
}
